﻿using Bricks.Business.Models.Account;
using Bricks.Business.Service;
using Bricks.Business.Service.CommonSupport;
using Bricks.Component.Utils;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models.OrgInfo;
using Bricks.Site.Models.Purview;
using Bricks.Site.Web.CommonUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 授权Controller
    /// 机构授权：左机构右授权
    /// 用户授权：左用户右授权
    /// 授权：即以上的授权UI
    /// </summary>
    [Export]
    public class PurviewController : BaseController
    {
        [Import]
        public IUserInfoService UserService { get; set; }

        [Import]
        public IPurviewService PurviewService { get; set; }

        [Import]
        public IOrgInfoService OrgInfoService { get; set; }

        [Import]
        public IUserOrgService UserOrgService { get; set; }

        [Import]
        public IRoleInfoService RoleInfoService { get; set; }

        [Import]
        public IMenuActionService MenuActionService { get; set; }

        #region 视图功能
        #region 机构授权
        /// <summary>
        /// 机构授权
        /// </summary>
        /// <returns></returns>
        public ActionResult OrgPurview()
        {
            //ViewBag.TreePanelInfo = base.GetPanelInfo();
            //ViewBag.TreeToolBarInfo = base.GetToolBarInfo();

            //http://localhost:54321/OrgInfo/Index?MenuID=290c8689-3d19-40c0-8af8-2014d3f8da4f

            //string menuID = Request["MenuID"] as string;  //取得机构菜单ID
            //string embedUrl = Request.Url.OriginalString.Replace("OrgPurview", "Purview").Replace(menuID, PurviewService.GetPurviewPageID());
            //ViewBag.EmbedInfo = HttpHelper.GetPageHtml("~/Account/Index?MenuID=b4965782-329a-4a33-82ec-a8353e7054eb", null);  //取用户管理嵌入窗体（此处需要更改地址获取方式）

            //Uri baseUri = new Uri(Request.Url.OriginalString);
            //Uri absolveUri = new Uri(baseUri, "Purview");
            ////string embedUrl = Path.GetFullPath("~/Purview/Purview");
            //string embedUrl = absolveUri.AbsoluteUri;
            //ViewBag.PurviewUI = HttpHelper.GetPageHtml(embedUrl, null);  //取用户管理嵌入窗体（此处需要更改地址获取方式）

            //从地址栏取得OrgID
            string orgID = Request["OrgID"] as string;
            ViewBag.SelectedOrgID = orgID;  //用于赋值给隐藏字段
            ViewBag.ConfigType = "OrgPurview";  //配置类型

            //以下处理上下文
            //定义HttpContext.Application["OrgPurviewDict"]承载的对象
            //对象Key为机构ID，值为机构对应的权限路径列表
            Dictionary<Guid, List<PurviewPathView>> orgPurviewDict = new Dictionary<Guid, List<PurviewPathView>>();
            List<PurviewPathView> dbList = PurviewService.GetOrgPurviewPath(orgID.ToGuid());  //获取所选机构的权限列表（从数据库获取）
            orgPurviewDict.Add(orgID.ToGuid(), dbList);  //将列表添加到上下文对象
            if (HttpContext.Application.AllKeys.Contains("OrgPurviewDict"))
            {
                HttpContext.Application.Remove("OrgPurviewDict");
            }
            HttpContext.Application.Add("OrgPurviewDict", orgPurviewDict);

            return View();
        }

        /// <summary>
        /// 机构授权保存（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OrgPurviewPost()
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");
            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains("OrgPurviewDict"))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appOrgPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["OrgPurviewDict"];
                if (appOrgPurviewDict != null)
                {
                    result = PurviewService.SaveOrgPurviewDict(appOrgPurviewDict);
                }
                HttpContext.Application.Remove("OrgPurviewDict");  //移除上下文对象（防止占用）
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取已选择的机构列表（获取机构列表后，将机构权限写入到上下文中）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSelectedOrgList(string orgID)
        {
            List<Guid> selectedOrgIDList = new List<Guid>();  //选择的orgID集合
            Dictionary<Guid, List<PurviewPathView>> appOrgPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["OrgPurviewDict"];  //取得上下文对象

            //如果选定了机构（可多个）
            if (!String.IsNullOrEmpty(orgID))
            {
                string[] selectedOrgArr = orgID.Split(',');  //转换为string数组
                foreach (string item in selectedOrgArr)
                {
                    selectedOrgIDList.Add(item.ToGuid());

                    //处理上下文对象 Start
                    //如果上下文对象不包含机构的ID，那么则将对应的机构和权限信息加入到上下文对象
                    if (!appOrgPurviewDict.Keys.Contains(item.ToGuid()))
                    {
                        List<PurviewPathView> dbList = PurviewService.GetOrgPurviewPath(item.ToGuid());  //获取机构的权限列表（从数据库获取）
                        appOrgPurviewDict.Add(item.ToGuid(), dbList);
                    }
                }
                //剔除上下文对象中未选择的多余机构及对应的机构权限
                var unSelectedOrgPurviewDict = appOrgPurviewDict.Where(m => !selectedOrgIDList.Contains(m.Key));  //获取多余机构Dict
                //如果存在多余机构，则循环剔除
                if (unSelectedOrgPurviewDict != null && unSelectedOrgPurviewDict.Count() > 0)
                {
                    List<Guid> unOrgguidIDList = new List<Guid>();  //多余机构的ID集合（采取这种临时方法可解决集合已被修改的异常）
                    foreach (var un in unSelectedOrgPurviewDict)  //异常：集合已修改？
                    {
                        unOrgguidIDList.Add(un.Key);  //添加到多余机构ID集合
                    }
                    foreach (Guid unOrgID in unOrgguidIDList)
                    {
                        appOrgPurviewDict.Remove(unOrgID);  //剔除上下文对应项
                    }
                }
                //处理上下文对象 End
            }
            //如果没选择机构了，则清空上下文对象
            else
            {
                appOrgPurviewDict.Clear();
            }
            //查找出已选择的机构记录（列表展示）
            var list = from m in OrgInfoService.Orgs
                       where selectedOrgIDList.Contains(m.ID)
                       orderby m.OrderNo
                       select new
                       {
                           ID = m.ID,
                           OrgName = m.OrgName
                       };
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 选择机构
        /// </summary>
        /// <param name="orgListJson">传递的</param>
        /// <returns></returns>
        public ActionResult ChooseOrg(string orgIDs)
        {
            //List<OrgChooseView> list = new List<OrgChooseView>();
            //DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(list.GetType());
            //byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(orgListJson);
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArr);
            //ms.Position = 0;
            //list = (List<OrgChooseView>)jsonSerializer.ReadObject(ms);
            //return Content(orgIDs);

            ViewBag.OrgIDs = orgIDs;  //将json传给前台的隐藏控件
            return View();
        }

        /// <summary>
        /// 选择机构（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChooseOrgPost()
        {
            //return View();
            //return Content("success");

            //var result = new OperationResult(OperationResultType.Success, "选择成功", null, selectedOrgIDs);
            var result = new OperationResult(OperationResultType.Success, "选择成功");
            return Json(result, "text/html");

            //return Content("Success");
            //return RedirectToAction("OrgPurview");
        }
        #endregion

        #region 用户授权
        /// <summary>
        /// 用户授权
        /// </summary>
        /// <returns></returns>
        public ActionResult UserPurview()
        {
            //Uri baseUri = new Uri(Request.Url.OriginalString);
            //Uri absolveUri = new Uri(baseUri, "Purview");
            //string embedUrl = absolveUri.AbsoluteUri;
            //ViewBag.PurviewUI = HttpHelper.GetPageHtml(embedUrl, null);  //取用户管理嵌入窗体（此处需要更改地址获取方式）

            //从地址栏取得OrgID
            string userOrgID = Request["UserOrgID"] as string;
            ViewBag.SelectedUserOrgID = userOrgID;  //用于赋值给隐藏字段
            ViewBag.ConfigType = "UserPurview";  //配置类型
            //以下处理上下文
            //定义HttpContext.Application["OrgPurviewDict"]承载的对象
            //对象Key为机构ID，值为机构对应的权限路径列表
            Dictionary<Guid, List<PurviewPathView>> userPurviewDict = new Dictionary<Guid, List<PurviewPathView>>();
            List<PurviewPathView> dbList = PurviewService.GetUserPurviewPath(userOrgID.ToGuid());  //获取所选用户的权限列表（从数据库获取）
            userPurviewDict.Add(userOrgID.ToGuid(), dbList);  //将列表添加到上下文对象
            if (HttpContext.Application.AllKeys.Contains("UserPurviewDict"))
            {
                HttpContext.Application.Remove("UserPurviewDict");
            }
            HttpContext.Application.Add("UserPurviewDict", userPurviewDict);

            return View();
        }

        /// <summary>
        /// 用户授权保存（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserPurviewPost()
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");
            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains("UserPurviewDict"))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appUserPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["UserPurviewDict"];
                if (appUserPurviewDict != null)
                {
                    result = PurviewService.SaveUserPurviewDict(appUserPurviewDict);
                }
                HttpContext.Application.Remove("UserPurviewDict");  //移除上下文对象（防止占用）
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取已选择的用户列表（获取用户列表后，将用户权限写入到上下文中）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSelectedUserOrgList(string userOrgID)
        {
            List<Guid> selectedUserOrgIDList = new List<Guid>();  //选择的userOrgID集合
            Dictionary<Guid, List<PurviewPathView>> appUserPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["UserPurviewDict"];  //取得上下文对象

            //如果选定了用户（可多个）
            if (!String.IsNullOrEmpty(userOrgID))
            {
                string[] selectedUserOrgArr = userOrgID.Split(',');  //转换为string数组
                foreach (string item in selectedUserOrgArr)
                {
                    selectedUserOrgIDList.Add(item.ToGuid());

                    //处理上下文对象 Start
                    //如果上下文对象不包含用户的ID，那么则将对应的用户和权限信息加入到上下文对象
                    if (!appUserPurviewDict.Keys.Contains(item.ToGuid()))
                    {
                        List<PurviewPathView> dbList = PurviewService.GetUserPurviewPath(item.ToGuid());  //获取用户的权限列表（从数据库获取）
                        appUserPurviewDict.Add(item.ToGuid(), dbList);
                    }
                }
                //剔除上下文对象中未选择的多余用户及对应的机构权限
                var unSelectedUserPurviewDict = appUserPurviewDict.Where(m => !selectedUserOrgIDList.Contains(m.Key));  //获取多余用户Dict
                //如果存在多余用户，则循环剔除
                if (unSelectedUserPurviewDict != null && unSelectedUserPurviewDict.Count() > 0)
                {
                    List<Guid> unUserguidIDList = new List<Guid>();  //多余用户的ID集合（采取这种临时方法可解决集合已被修改的异常）
                    foreach (var un in unSelectedUserPurviewDict)  //异常：集合已修改？
                    {
                        unUserguidIDList.Add(un.Key);  //添加到多余用户ID集合
                    }
                    foreach (Guid unUserID in unUserguidIDList)
                    {
                        appUserPurviewDict.Remove(unUserID);  //剔除上下文对应项
                    }
                }
                //处理上下文对象 End
            }
            //如果没选择用户了，则清空上下文对象
            else
            {
                appUserPurviewDict.Clear();
            }
            //查找出已选择的用户记录（列表展示）
            //var list = from m in UserInfoService.Users
            //           where selectedUserOrgIDList.Contains(m.ID)
            //           orderby m.UserName
            //           select new
            //           {
            //               ID = m.ID,
            //               UserName = m.UserName,
            //               OrgName = 
            //           };
            var list = from uo in UserOrgService.UserOrgs
                       join u in UserInfoService.Users on uo.UserID equals u.ID
                       join o in OrgInfoService.Orgs on uo.OrgID equals o.ID
                       where selectedUserOrgIDList.Contains(uo.ID)
                       select new
                       {
                           ID = uo.ID,
                           UserName = u.UserName,
                           OrgName = o.OrgName,

                           UserID = u.ID
                       };
            list = list.OrderBy(m => m.UserName);
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 选择用户
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        public ActionResult ChooseUser(string userOrgIDs)
        {
            //CheckedUserOrgIDList用于保存已选择的用户机构ID
            if (HttpContext.Application.AllKeys.Contains("CheckedUserOrgIDList"))
            {
                HttpContext.Application.Remove("CheckedUserOrgIDList");
            }
            List<Guid> checkedUserOrgIDList = new List<Guid>();
            if (!String.IsNullOrEmpty(userOrgIDs))
            {
                string[] checkedUserIDArray = userOrgIDs.Split(',');
                if (checkedUserIDArray != null && checkedUserIDArray.Length > 0)
                {
                    foreach (var item in checkedUserIDArray)
                    {
                        checkedUserOrgIDList.Add(item.ToGuid());
                    }
                }
            }
            HttpContext.Application.Add("CheckedUserOrgIDList", checkedUserOrgIDList);
            return View();
        }

        /// <summary>
        /// 用户勾选/取消勾选
        /// </summary>
        /// <param name="userOrgID"></param>
        /// <param name="isChecked"></param>
        /// <returns></returns>
        public ActionResult ChangeUserChecked(string userOrgID, string isChecked)
        {
            if (HttpContext.Application.AllKeys.Contains("CheckedUserOrgIDList"))
            {
                List<Guid> checkedUserOrgIDList = HttpContext.Application["CheckedUserOrgIDList"] as List<Guid>;
                if (checkedUserOrgIDList != null)
                {
                    //勾选
                    if (isChecked == "true")
                    {
                        checkedUserOrgIDList.Add(userOrgID.ToGuid());
                    }
                    //取消勾选
                    else
                    {
                        if (checkedUserOrgIDList.Contains(userOrgID.ToGuid()))
                        {
                            checkedUserOrgIDList.Remove(userOrgID.ToGuid());
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 获取用户列表数据（不分页）
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        public ActionResult GetUserDataListNoPage(string orgID = null)
        {
            //识别第一次加载，不进行任何数据加载
            if (orgID.Equals("unknow"))
            {
                return null;
            }
            var query = UserService.GetUsersByOrgIDNoPage(orgID.ToGuid());
            if (query != null)
            {
                if (HttpContext.Application.AllKeys.Contains("CheckedUserOrgIDList"))
                {
                    List<Guid> checkedUserOrgIDList = HttpContext.Application["CheckedUserOrgIDList"] as List<Guid>;
                    var checkedUsers = query.Where(m => checkedUserOrgIDList.Contains(m.UserOrgID.HasValue ? m.UserOrgID.Value : Guid.Empty));
                    if (checkedUsers != null && checkedUsers.Count() > 0)
                    {
                        foreach (var item in checkedUsers)
                        {
                            item.IsChecked = true;
                        }
                    }
                }
            }
            return Json(query, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 选择用户（Post）
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseUserPost()
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            object selectedUserOrgIDs = string.Empty;
            try
            {
                if (HttpContext.Application.AllKeys.Contains("CheckedUserOrgIDList"))
                {
                    List<Guid> checkedUserOrgIDList = HttpContext.Application["CheckedUserOrgIDList"] as List<Guid>;
                    if (checkedUserOrgIDList != null)
                    {
                        selectedUserOrgIDs = string.Join(",", checkedUserOrgIDList);
                    }
                    HttpContext.Application.Remove("CheckedUserOrgIDList");  //移除上下文对象
                }
                result = new OperationResult(OperationResultType.Success, "选择成功", selectedUserOrgIDs);
            }
            catch (Exception ex)
            {
                result = new OperationResult(OperationResultType.Error, ex.Message);
            }
            return Json(result, "text/html");
        }
        #endregion

        #region 权限组授权
        public ActionResult RolePurview()
        {
            //从地址栏取得OrgID
            string roleID = Request["RoleID"] as string;
            ViewBag.SelectedRoleID = roleID;  //用于赋值给隐藏字段
            ViewBag.ConfigType = "RolePurview";  //配置类型

            //以下处理上下文
            //定义HttpContext.Application["OrgPurviewDict"]承载的对象
            //对象Key为机构ID，值为机构对应的权限路径列表
            Dictionary<Guid, List<PurviewPathView>> rolePurviewDict = new Dictionary<Guid, List<PurviewPathView>>();
            List<PurviewPathView> dbList = PurviewService.GetRolePurviewPath(roleID.ToGuid());  //获取所选机构的权限列表（从数据库获取）
            rolePurviewDict.Add(roleID.ToGuid(), dbList);  //将列表添加到上下文对象
            if (HttpContext.Application.AllKeys.Contains("RolePurviewDict"))
            {
                HttpContext.Application.Remove("RolePurviewDict");
            }
            HttpContext.Application.Add("RolePurviewDict", rolePurviewDict);

            return View();
        }

        /// <summary>
        /// 权限组授权保存（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RolePurviewPost()
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");
            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains("RolePurviewDict"))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appRolePurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["RolePurviewDict"];
                if (appRolePurviewDict != null)
                {
                    result = PurviewService.SaveRolePurviewDict(appRolePurviewDict);
                }
                HttpContext.Application.Remove("RolePurviewDict");  //移除上下文对象（防止占用）
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取已选择的权限组列表（获取权限组列表后，将权限组权限写入到上下文中）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSelectedRoleList(string roleID)
        {
            List<Guid> selectedRoleIDList = new List<Guid>();  //选择的roleId集合
            Dictionary<Guid, List<PurviewPathView>> appRolePurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application["RolePurviewDict"];  //取得上下文对象

            //如果选定了权限组（可多个）
            if (!String.IsNullOrEmpty(roleID))
            {
                string[] selectedRoleArr = roleID.Split(',');  //转换为string数组
                foreach (string item in selectedRoleArr)
                {
                    selectedRoleIDList.Add(item.ToGuid());

                    //处理上下文对象 Start
                    //如果上下文对象不包含机构的ID，那么则将对应的权限组和权限信息加入到上下文对象
                    if (!appRolePurviewDict.Keys.Contains(item.ToGuid()))
                    {
                        List<PurviewPathView> dbList = PurviewService.GetRolePurviewPath(item.ToGuid());  //获取权限组的权限列表（从数据库获取）
                        appRolePurviewDict.Add(item.ToGuid(), dbList);
                    }
                }
                //剔除上下文对象中未选择的多余权限组及对应的权限组权限
                var unSelectedRolePurviewDict = appRolePurviewDict.Where(m => !selectedRoleIDList.Contains(m.Key));  //获取多余权限组Dict
                //如果存在多余权限组，则循环剔除
                if (unSelectedRolePurviewDict != null && unSelectedRolePurviewDict.Count() > 0)
                {
                    List<Guid> unRoleguidIDList = new List<Guid>();  //多余机构的ID集合（采取这种临时方法可解决集合已被修改的异常）
                    foreach (var un in unSelectedRolePurviewDict)  //异常：集合已修改？
                    {
                        unRoleguidIDList.Add(un.Key);  //添加到多余权限组ID集合
                    }
                    foreach (Guid unOrgID in unRoleguidIDList)
                    {
                        appRolePurviewDict.Remove(unOrgID);  //剔除上下文对应项
                    }
                }
                //处理上下文对象 End
            }
            //如果没选择权限组了，则清空上下文对象
            else
            {
                appRolePurviewDict.Clear();
            }
            //查找出已选择的权限组记录（列表展示）
            var list = from m in RoleInfoService.Roles
                       where selectedRoleIDList.Contains(m.ID)
                       orderby m.OrderNo
                       select new
                       {
                           ID = m.ID,
                           RoleName = m.RoleName
                       };
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 选择机构
        /// </summary>
        /// <param name="orgListJson">传递的</param>
        /// <returns></returns>
        public ActionResult ChooseRole(string roleIDs)
        {
            //List<OrgChooseView> list = new List<OrgChooseView>();
            //DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(list.GetType());
            //byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(orgListJson);
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArr);
            //ms.Position = 0;
            //list = (List<OrgChooseView>)jsonSerializer.ReadObject(ms);
            //return Content(orgIDs);

            ViewBag.RoleIDs = roleIDs;  //将json传给前台的隐藏控件
            return View();
        }

        /// <summary>
        /// 选择机构（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChooseRolePost()
        {
            //return View();
            //return Content("success");

            //var result = new OperationResult(OperationResultType.Success, "选择成功", null, selectedOrgIDs);
            var result = new OperationResult(OperationResultType.Success, "选择成功");
            return Json(result, "text/html");

            //return Content("Success");
            //return RedirectToAction("OrgPurview");
        }
        #endregion

        #region 授权（嵌入机构授权、用户授权、权限组授权）
        /// <summary>
        /// 授权
        /// </summary>
        /// <returns></returns>
        public ActionResult Purview()
        {
            return View();
        }

        /// <summary>
        /// 获取选中的机构/用户的权限路径
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="isUserPurview"></param>
        /// <returns></returns>
        public ActionResult GetSelectedOrgPurviewPathList(string instanceID, string configType)
        {
            List<PurviewPathView> resultList = new List<PurviewPathView>();

            string dictName = "OrgPurviewDict";  //定义字典名称
            //如果是用户授权，则字典名称为UserPurviewDict
            if (configType == "UserPurview")
            {
                dictName = "UserPurviewDict";
            }
            else if (configType == "RolePurview")
            {
                dictName = "RolePurviewDict";
            }

            //如果选中了
            if (!String.IsNullOrEmpty(instanceID))
            {
                //从上下文查找OrgPurviewDict
                if (HttpContext.Application.AllKeys.Contains(dictName))
                {
                    Dictionary<Guid, List<PurviewPathView>> appInstancePurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application[dictName];  //取得上下文对象
                    if (appInstancePurviewDict != null)
                    {
                        Guid guidInstanceID = instanceID.ToGuid();
                        if (appInstancePurviewDict.ContainsKey(guidInstanceID))
                        {
                            var selectedInstancePurviewList = appInstancePurviewDict[guidInstanceID].OrderBy(m => m.PurviewPath);  //从上下文对象中取得选择机构的权限，按路径排序
                            if (selectedInstancePurviewList != null)
                            {
                                resultList.AddRange(selectedInstancePurviewList);  //添加到结果List
                            }
                        }
                    }
                }
            }
            return Json(resultList, JsonRequestBehavior.AllowGet);  //返回结果List
        }

        /// <summary>
        /// 选择权限
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="configType"></param>
        /// <returns></returns>
        public ActionResult ChoosePurview(string instanceID, string configType)
        {
            //如果orgIDs为空，表示是批量选择权限入口进入
            //读取所有MenuAction，然后加入到上下文对象中
            if (String.IsNullOrEmpty(instanceID))
            {
                List<MenuActionView> appMenuActionList = PurviewService.GetMenuActionList();
                //如果上下文包含MenuActionList对象，则先做移除操作
                if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
                {
                    HttpContext.Application.Remove("MenuActionList");
                }
                HttpContext.Application.Add("MenuActionList", appMenuActionList);
            }
            //否则，表示是单独选择权限入口进入
            //读取对应机构的MenuAction
            else
            {
                string dictName = "OrgPurviewDict";
                if (configType == "UserPurview")
                {
                    dictName = "UserPurviewDict";
                }
                else if (configType == "RolePurview")
                {
                    dictName = "RolePurviewDict";
                }
                //从上下文的机构权限字典OrgPurviewDict中，将数据传给上下文MenuActionList
                //从上下文查找OrgPurviewDict
                if (HttpContext.Application.AllKeys.Contains(dictName))
                {
                    Dictionary<Guid, List<PurviewPathView>> appOrgPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application[dictName];  //取得上下文对象
                    if (appOrgPurviewDict != null)
                    {
                        Guid instanceGuid = instanceID.ToGuid();
                        if (appOrgPurviewDict.Keys.Contains(instanceGuid))
                        {
                            List<PurviewPathView> selectedInstancePurview = appOrgPurviewDict[instanceGuid];  //选中的权限路径

                            List<MenuActionView> appMenuActionList = PurviewService.GetMenuActionList();
                            foreach (var item in appMenuActionList)
                            {
                                var existOrgPurview = selectedInstancePurview.Count(m => m.MenuActionID == item.ID) > 0;
                                if (existOrgPurview)
                                {
                                    item.IsChecked = true;
                                }
                            }

                            //如果上下文包含MenuActionList对象，则先做移除操作
                            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
                            {
                                HttpContext.Application.Remove("MenuActionList");
                            }
                            HttpContext.Application.Add("MenuActionList", appMenuActionList);
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 选择权限（POST）
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        //[HttpPost]
        //public ActionResult ChoosePurviewPost(string orgIDs)
        //{
        //    return View();
        //}

        /// <summary>
        /// 获取菜单对应的功能
        /// </summary>
        /// <param name="menuID"></param>
        /// <returns></returns>
        public ActionResult GetMenuActionList(string menuID)
        {
            //var list = PurviewService.GetMenuActionList(menuID.ToGuid());
            //return Json(list, JsonRequestBehavior.AllowGet);

            List<MenuActionView> list = new List<MenuActionView>();
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    Guid guidMenuID = menuID.ToGuid();
                    //根据menuID进行过滤
                    list = appMenuActionList.Where(m => m.MenuID == guidMenuID).ToList();
                }
            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 变更勾选状态（将状态写入到缓存中）
        /// </summary>
        /// <param name="menuActionID">菜单功能ID</param>
        /// <param name="isChecked">是否勾选</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangeChecked(string menuActionID, string isChecked)
        {
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    Guid guidMenuActionID = menuActionID.ToGuid();
                    //根据menuActionID进行过滤
                    var record = appMenuActionList.FirstOrDefault(m => m.ID == guidMenuActionID);
                    if (record != null)
                    {
                        //设置上下文对象的IsChecked
                        record.IsChecked = isChecked == "true" ? true : false;
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 全选/取消全选菜单功能
        /// </summary>
        /// <param name="menuID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChooseAll(string menuID, string isChecked)
        {
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    Guid menuGuid = menuID.ToGuid();
                    //根据menuActionID进行过滤
                    var records = appMenuActionList.Where(m => m.MenuID == menuGuid);
                    if (records != null && records.Count() > 0)
                    {
                        //设置上下文对象的IsChecked
                        foreach (var record in records)
                        {
                            record.IsChecked = isChecked == "true" ? true : false;
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 反选
        /// </summary>
        /// <param name="menuID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OppositeChoose(string menuID)
        {
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    Guid menuGuid = menuID.ToGuid();
                    //根据menuActionID进行过滤
                    var records = appMenuActionList.Where(m => m.MenuID == menuGuid);
                    if (records != null && records.Count() > 0)
                    {
                        //设置上下文对象的IsChecked
                        foreach (var record in records)
                        {
                            record.IsChecked = !record.IsChecked;
                            //record.IsChecked = isChecked == "true" ? true : false;
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 覆盖权限
        /// </summary>
        /// <param name="instanceID">机构ID（单个设置权限时使用）</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CoverPurviewPost(string instanceID, string configType)
        {
            /*对以下两个对象进行处理
             * 机构权限：HttpContext.Application["OrgPurviewDict"]
             * 菜单功能：HttpContext.Application["MenuActionList"]
             * 覆盖则将选中的菜单功能，覆盖到OrgPurviewDict所有机构
             */

            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");

            //非超级管理员不允许执行覆盖操作（因为可能会覆盖掉其他权限）
            if (SystemData.Instance.CurrentUser.UserType != UserType.SuperAdmin)
            {
                result = new OperationResult(OperationResultType.Warning, "非超级管理员不允许执行覆盖操作");
                return Json(result, "text/html");
            }

            string dictName = "OrgPurviewDict";
            if (configType == "UserPurview")
            {
                dictName = "UserPurviewDict";
            }
            else if (configType == "RolePurview")
            {
                dictName = "RolePurviewDict";
            }

            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains(dictName) && HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appInstancePurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application[dictName];
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;

                if (appInstancePurviewDict != null && appMenuActionList != null)
                {
                    //orgID为空时，表示是批量覆盖
                    if (String.IsNullOrEmpty(instanceID))
                    {
                        //循环上下文机构权限字典
                        foreach (var op in appInstancePurviewDict)
                        {
                            op.Value.Clear();  //清空原来的权限列表
                            //循环上下文菜单功能列表
                            foreach (var ma in appMenuActionList)
                            {
                                //只添加选中的记录
                                if (!ma.IsChecked)
                                    continue;

                                PurviewPathView newOP = new PurviewPathView();

                                //如果是用户权限，需要根据UserOrgID获取UserID
                                //newOP.InstanceID = op.Key;
                                if (configType != "UserPurview")
                                    newOP.InstanceID = op.Key;
                                else
                                    newOP.InstanceID = PurviewService.GetUserIDByUserOrgID(op.Key);
                                newOP.MenuActionID = ma.ID;
                                newOP.PurviewPath = PurviewService.GetPurviewPath(ma.MenuID, ma.ActionName);  //取得全路径（只是显示权限路径时使用）
                                op.Value.Add(newOP);
                            }
                        }
                    }
                    //orgID不为空时，表示是单个设置*（等同单个覆盖）
                    else
                    {
                        Guid instanceGuid = instanceID.ToGuid();
                        if (appInstancePurviewDict.Keys.Contains(instanceGuid))
                        {
                            var purview = appInstancePurviewDict[instanceGuid];
                            purview.Clear();  //清空原来的权限列表
                            //循环上下文菜单功能列表
                            foreach (var ma in appMenuActionList)
                            {
                                //只添加选中的记录
                                if (!ma.IsChecked)
                                    continue;

                                PurviewPathView newOP = new PurviewPathView();

                                //如果是用户权限，需要根据UserOrgID获取UserID
                                //newOP.InstanceID = instanceGuid;
                                if (configType != "UserPurview")
                                    newOP.InstanceID = instanceGuid;
                                else
                                    newOP.InstanceID = PurviewService.GetUserIDByUserOrgID(instanceGuid);
                                newOP.MenuActionID = ma.ID;
                                newOP.PurviewPath = PurviewService.GetPurviewPath(ma.MenuID, ma.ActionName);  //取得全路径（只是显示权限路径时使用）
                                purview.Add(newOP);
                            }
                        }
                    }
                    //result = new OperationResult(OperationResultType.Success, "覆盖成功，请点击确认提交至数据库");
                    result = new OperationResult(OperationResultType.Success, !String.IsNullOrEmpty(instanceID) ? "操作成功，请点击确认提交至数据库" : "覆盖成功，请点击确认提交至数据库");
                }
                HttpContext.Application.Remove("MenuActionList");  //及时移除上下文对象MenuActionList
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 追加权限
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AppendPurviewPost(string configType)
        {
            /*对以下两个对象进行处理
             * 机构权限：HttpContext.Application["OrgPurviewDict"]
             * 菜单功能：HttpContext.Application["MenuActionList"]
             * 追加则将选中的菜单功能，追加到OrgPurviewDict中（已有的跳过，没有的增加）
             */
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");

            string dictName = "OrgPurviewDict";
            if (configType == "UserPurview")
            {
                dictName = "UserPurviewDict";
            }
            else if (configType == "RolePurview")
            {
                dictName = "RolePurviewDict";
            }

            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains(dictName) && HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appOrgPurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application[dictName];
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;

                if (appOrgPurviewDict != null && appMenuActionList != null)
                {
                    //循环上下文机构权限字典
                    foreach (var op in appOrgPurviewDict)
                    {
                        //op.Value.Clear();  //清空原来的权限列表
                        //循环上下文菜单功能列表
                        foreach (var ma in appMenuActionList)
                        {
                            //只添加选中的记录
                            if (!ma.IsChecked)
                                continue;

                            var existOP = op.Value.Count(m => m.MenuActionID == ma.ID) > 0;  //查找原来是否存在
                            //如果不存在，则增加到列表中
                            if (!existOP)
                            {
                                PurviewPathView newOP = new PurviewPathView();

                                //如果是用户权限，需要根据UserOrgID获取UserID
                                //newOP.InstanceID = op.Key;
                                if (configType != "UserPurview")
                                    newOP.InstanceID = op.Key;
                                else
                                    newOP.InstanceID = PurviewService.GetUserIDByUserOrgID(op.Key);
                                newOP.MenuActionID = ma.ID;
                                newOP.PurviewPath = PurviewService.GetPurviewPath(ma.MenuID, ma.ActionName);  //取得全路径（只是显示权限路径时使用）
                                op.Value.Add(newOP);
                            }
                        }
                    }
                    result = new OperationResult(OperationResultType.Success, "追加成功，请点击确认提交至数据库");
                    //result = new OperationResult(OperationResultType.Success, isAlone.Equals("true") ? "操作成功，请点击确认提交至数据库" : "追加成功，请点击确认提交至数据库");
                }
                HttpContext.Application.Remove("MenuActionList");  //及时移除上下文对象MenuActionList
            }
            return Json(result, "text/html");
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="menuActionID"></param>
        /// <returns></returns>
        public ActionResult DeletePurview(string instanceID, string menuActionID, string configType)
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "NoChanged");

            //非超级管理员不允许执行权限删除操作（因为可能会删除掉其他权限）
            //if (SystemData.Instance.CurrentUser.UserType != UserType.SuperAdmin)
            //{
            //    result = new OperationResult(OperationResultType.Warning, "非超级管理员不允许执行删除操作，您可尝试在\"单独选择权限\"中去除部分权限");
            //    return Json(result, "text/html");
            //}

            string dictName = "OrgPurviewDict";
            if (configType == "UserPurview")
            {
                dictName = "UserPurviewDict";
            }
            else if (configType == "RolePurview")
            {
                dictName = "RolePurviewDict";
            }

            //从上下文查找OrgPurviewDict
            if (HttpContext.Application.AllKeys.Contains(dictName))
            {
                //取得上下文对象
                Dictionary<Guid, List<PurviewPathView>> appInstancePurviewDict = (Dictionary<Guid, List<PurviewPathView>>)HttpContext.Application[dictName];
                if (appInstancePurviewDict != null)
                {
                    Guid instanceGuid = instanceID.ToGuid();
                    if (appInstancePurviewDict.Keys.Contains(instanceGuid))
                    {
                        Guid menuActionGuid = menuActionID.ToGuid();
                        var purview = appInstancePurviewDict[instanceGuid].FirstOrDefault(m => m.MenuActionID == menuActionGuid);
                        if (purview != null)
                        {
                            appInstancePurviewDict[instanceGuid].Remove(purview);
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 权限组选择变更（将权限组的权限给界面）
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleChangedPost(string roleID)
        {
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    Guid guidRoleID = roleID.ToGuid();
                    //找出权限组对应的权限
                    var roleMenuActions = RoleInfoService.RoleMenuActions.Where(m => m.RoleID == guidRoleID);
                    //如果找到权限，则循环界面上的元素，找到则勾选，找不到则不勾选
                    if (roleMenuActions != null && roleMenuActions.Count() > 0)
                    {
                        foreach (var item in appMenuActionList)
                        {
                            var isExist = roleMenuActions.Count(m => m.MenuActionID == item.ID) > 0;
                            if (isExist)
                            {
                                item.IsChecked = true;
                            }
                            else
                            {
                                item.IsChecked = false;
                            }
                        }
                    }
                    //如果没有找到，说明权限组的权限为空，那么也去除勾选目前所有的权限
                    else
                    {
                        foreach (var item in appMenuActionList)
                        {
                            item.IsChecked = false;
                        }
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 获取菜单功能路径列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenuActionPathList()
        {
            List<PurviewPathView> resultList = new List<PurviewPathView>();
            if (HttpContext.Application.AllKeys.Contains("MenuActionList"))
            {
                //从上下文取得对象
                List<MenuActionView> appMenuActionList = HttpContext.Application["MenuActionList"] as List<MenuActionView>;
                if (appMenuActionList != null)
                {
                    PurviewPathView newPath = null;
                    foreach (var item in appMenuActionList)
                    {
                        if (!item.IsChecked)
                            continue;

                        newPath = new PurviewPathView();
                        newPath.PurviewPath = PurviewService.GetPurviewPath(item.MenuID, item.ActionName);  //构造完整路径
                        resultList.Add(newPath);
                    }
                }
            }
            resultList = resultList.OrderBy(m => m.PurviewPath).ToList();
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取权限组权限路径列表
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ActionResult GetRoleMenuActionPathList(string roleID)
        {
            List<PurviewPathView> resultList = new List<PurviewPathView>();
            Guid guidRoleID = roleID.ToGuid();
            var roleMenuActions = RoleInfoService.RoleMenuActions.Where(m => m.RoleID == guidRoleID);
            if (roleMenuActions != null && roleMenuActions.Count() > 0)
            {
                PurviewPathView newPath = null;
                foreach (var item in roleMenuActions)
                {
                    var menuAction = MenuActionService.GetMenuActionByID(item.MenuActionID);
                    if (menuAction != null)
                    {
                        newPath = new PurviewPathView();
                        newPath.PurviewPath = PurviewService.GetPurviewPath(menuAction.MenuID, menuAction.ActionName);  //构造完整路径
                        resultList.Add(newPath);
                    }
                }
            }
            resultList = resultList.OrderBy(m => m.PurviewPath).ToList();
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #endregion
    }
}
